/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.core.util;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Reflection related helper utilities.
 *
 * @author Xiaohai Zhang
 * @since 2013-08-20 11:22
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
abstract public class ReflectionUtils {
    @RequiredArgsConstructor
    public static class ClassField {
        @NonNull @Getter private final Class<?> clazz;
        @NonNull @Getter private final Field field;

        public String getFieldName() {
            return field.getName();
        }

        public boolean isStaticField() {
            return Modifier.isStatic(field.getModifiers());
        }

        public boolean isFinalField() {
            return Modifier.isFinal(field.getModifiers());
        }
    }

    // same name field will be kept only once, will abandon duplicated ones from parent
    public static List<ClassField> getAllFields(Class<?> source) {
        Assert.notNull(source);
        Map<String, ClassField> fields = new LinkedHashMap<>();
        for (Class<?> clazz : ClassUtils.getClassInheritanceHierachy(source)) {
            if (clazz == Object.class) {
                // ignore Object.class
                continue;
            }
            for (Field field : clazz.getDeclaredFields()) {
                ClassField classField = new ClassField(clazz, field);
                if (fields.containsKey(classField.getFieldName()) && !StringUtils.equals(classField.getFieldName(), "serialVersionUID")) {
                    ReflectionUtils.log.warn("Same name field '{}' found in '{}'", field.getName(), clazz.getName());
                }
                fields.put(classField.getFieldName(), classField);
            }
        }
        return new LinkedList<>(fields.values());
    }
}
